package ua.org.extjsbuilder.parser.scanner;

import java.util.LinkedList;
import java.util.List;

import ua.org.extjsbuilder.parser.IToken;
import ua.org.extjsbuilder.parser.ITokenScanner;
import ua.org.extjsbuilder.parser.runtime.UnparsedToken;

public class LinesScanner implements ITokenScanner {

	public void finish(){}

	public void init(){}

	public void scan(IToken token) {
		if(token instanceof UnparsedToken){
			splitOnLines((UnparsedToken)token);
		}
	}
	
	private void splitOnLines(UnparsedToken token){
		char[] data = token.getData();
		int len = data.length;
		int line = 1;
		int start = 0;
		List<IToken> result = new LinkedList<IToken>();
		for(int i=0;i<len;i++){
			char c = data[i];
			if(c=='\r'||c=='\n'){
				result.add(new UnparsedToken(data,start,i,line++));
				if(c=='\r'&&i+1<len&&data[i+1]=='\n'){
					i++;
				}
				start = i+1;
			}
		}
		result.add(new UnparsedToken(data,start,len,line));
		token.split(result.toArray(
			new IToken[result.size()]));
	}
}
